import React, { Component } from 'react'
import { BrowserRouter as Router, withRouter } from 'react-router-dom';

let prevLocation, location, action, unBlock;

class _GuardHelper extends Component {

    componentDidMount() {
        // 添加阻塞
        unBlock = this.props.history.block((newLocation, ac) => {
            prevLocation = this.props.location;
            location = newLocation;
            action = ac;
            return '';
        });

        this.unListen = this.props.history.listen((location, action) => {
            if (this.props.onChange) {
                const prevLocation = this.props.location;
                this.props.onChange(prevLocation, location, action, this.unListen)
            }
        })
    }

    componentWillUnmount() {
        unBlock(); // 取消阻塞
        // 卸载监听器
        this.unListen();
    }

    render() {
        return null;
    }
}

const GuardHelper = withRouter(_GuardHelper);

class RouteGuard extends Component {

    handleConfirm = (msg, commit) => {
        if (this.props.onBeforeChange) {
            this.props.onBeforeChange(prevLocation, location, action, commit, unBlock);
        }
    }

    render() {
        return <Router getUserConfirmation={this.handleConfirm}>
            <GuardHelper />
            {this.props.children}
        </Router>;
    }
}

export default RouteGuard;
